package com.xian.im.common.utils.sys;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class SpringContextHolder implements ApplicationContextAware, EnvironmentAware {

    private static ApplicationContext applicationContext;
    private static Environment environment;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }


    public static  <T> T getBean(String beanName){
        return (T) applicationContext.getBean(beanName);
    }


    public static <T> T getBean(Class<T> clazz){
        return (T) applicationContext.getBean(clazz);
    }

    @Override
    public void setEnvironment(Environment environment) {
        SpringContextHolder.environment = environment;
    }

    public static String getProperty(String key, String defaultValue){
        return environment.getProperty(key,defaultValue);
    }

    public static String getProperty(String key){
        return environment.getProperty(key);
    }
}
